// pages/function_test/large_file_transfer/index.ts
import { RCSPOpLargeFileTransfer } from "../../../lib/rcsp-impl/rcsp"
import { OPFile, OPLargerFileTrans, StringUtil } from "../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        fileName: undefined,
        filePath: "请选择文件",
        transferContent: "传输未开始"
    },
    sdCardBean: OPFile.SDCardBean.prototype,
    transferContent: "传输未开始",
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        //    console.log(ab2hex( stringToData(2,"bg_src.png")));


        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            const sdCardBean = data.data as OPFile.SDCardBean | undefined
            if (sdCardBean) {
                console.log(" sdCardBean: ", sdCardBean);
                this.sdCardBean = sdCardBean
                // RCSPOpDirectoryBrowse?.appendBrowse(file).then(_devFolder => {
                //     const rootFolder = _devFolder.listFile()?.[0]
                //     if (rootFolder) {
                //         currentFile = rootFolder
                //         RCSPOpDirectoryBrowse?.appendBrowse(rootFolder).then(_rootFolder => {
                //             this._handleFileList(_rootFolder)
                //         })
                //     }
                // })
            }
        })
    },
    onShow() {
        this.setData({
            transferContent: this.transferContent
        })
    },
    onUnload() {
        RCSPOpLargeFileTransfer?.cancelTransfer()
    },
    onHide() {
        console.error("取消传输");
        RCSPOpLargeFileTransfer?.cancelTransfer()
    },
    onSelectFile() {
        console.log(" isfree:" + RCSPOpLargeFileTransfer?.isFree());
        if (!RCSPOpLargeFileTransfer?.isFree()) {
            return
        }
        wx.chooseMessageFile({
            count: 1,
            success: (res) => {
                const tempFilePaths = res.tempFiles
                console.log("tempFilePaths : ", tempFilePaths);
                this.setData({
                    filePath: tempFilePaths[0].path
                })
                const fs = wx.getFileSystemManager()
                fs.getFileInfo({
                    filePath: tempFilePaths[0].path,
                    success: (res) => {
                        let fd = fs.openSync({
                            filePath: tempFilePaths[0].path
                        })
                        let uint8 = new Uint8Array(res.size);
                        fs.read({
                            fd: fd,
                            arrayBuffer: uint8.buffer,
                            length: res.size,
                            success: (_res) => {
                                console.log("读取文件成功", uint8);
                                wx.showModal({
                                    title: "输入文件名",
                                    editable: true,
                                    content: tempFilePaths[0].name,
                                    success: (res) => {
                                        if (res.confirm) {
                                            const fileName = res.content
                                            const callback: OPLargerFileTrans.TransferTaskCallback = {
                                                onError: (code) => {
                                                    this.transferContent = "传输失败,code:" + code
                                                    this.setData({
                                                        transferContent: this.transferContent
                                                    })
                                                }, onStart: () => {
                                                    this.transferContent = "传输开始"
                                                    this.setData({
                                                        transferContent: this.transferContent
                                                    })
                                                }, onProgress: (progress) => {
                                                    this.transferContent = "传输进度:" + progress
                                                    this.setData({
                                                        transferContent: this.transferContent
                                                    })
                                                }, onCancel: (code) => {
                                                    this.transferContent = "传输任务取消:" + (code == 0 ? "App取消" : "设备取消")

                                                    this.setData({
                                                        transferContent: this.transferContent
                                                    })
                                                }, onSuccess: () => {
                                                    this.transferContent = "传输完成"
                                                    this.setData({
                                                        transferContent: this.transferContent
                                                    })
                                                }
                                            }
                                            // let fileName = tempFilePaths[0].name
                                            // if (this.data.fileName != undefined) {
                                            //     //@ts-ignore
                                            //     fileName = this.data.fileName
                                            // } else {
                                                this.setData({
                                                    //@ts-ignore 
                                                    fileName: fileName
                                                })
                                            // }

                                            const fileNameData = StringUtil.stringToData(2, fileName)
                                            const isFlash = this.sdCardBean.index == OPFile.SDCardBean.INDEX_FLASH
                                            if ((fileNameData.byteLength > 12||fileNameData.length > 12) && isFlash) {
                                                this.transferContent = "传输失败,flash设备不能传输长文件名文件（文件名字节长度小于12）"
                                                this.setData({
                                                    transferContent: this.transferContent
                                                })
                                            } else {
                                                RCSPOpLargeFileTransfer?.excuteTransferTask({
                                                    fileBuffer: uint8,
                                                    sdCardBean: this.sdCardBean,
                                                    isSupportPackageCrc16: true,
                                                    fileName: fileName,
                                                    lastModifyTime: tempFilePaths[0].time,
                                                    fileNameEncodeFormat: 0,
                                                    callback
                                                })
                                            }
                                        }
                                    }
                                })


                                // const callback: OPLargerFileTrans.TransferTaskCallback = {
                                //     onError: (code) => {
                                //         this.transferContent ="传输失败,code:" + code
                                //         this.setData({
                                //             transferContent:  this.transferContent
                                //         })
                                //     }, onStart: () => {
                                //         this.transferContent = "传输开始"
                                //         this.setData({
                                //             transferContent:  this.transferContent
                                //         })
                                //     }, onProgress: (progress) => {
                                //         this.transferContent = "传输进度:" + progress
                                //         this.setData({
                                //             transferContent:  this.transferContent
                                //         })
                                //     }, onCancel: (code) => {
                                //         this.transferContent = "传输任务取消:" + (code == 0 ? "App取消" : "设备取消")

                                //         this.setData({
                                //             transferContent:  this.transferContent
                                //         })
                                //     }, onSuccess: () => {
                                //         this.transferContent = "传输完成"
                                //         this.setData({
                                //             transferContent:  this.transferContent
                                //         })
                                //     }
                                // }
                                // let fileName = tempFilePaths[0].name
                                // if (this.data.fileName != undefined) {
                                //     //@ts-ignore
                                //     fileName = this.data.fileName
                                // } else {
                                //     this.setData({
                                //         //@ts-ignore 
                                //         fileName: fileName
                                //     })
                                // }
                                // const fileNameData = StringUtil.stringToData(2, fileName)
                                // const isFlash = this.sdCardBean.index == OPFile.SDCardBean.INDEX_FLASH
                                // if (fileNameData.byteLength > 12 && isFlash) {
                                //     this.transferContent = "传输失败,flash设备不能传输长文件名文件（文件名字节长度小于12）"
                                //     this.setData({
                                //         transferContent:  this.transferContent
                                //     })
                                // } else {
                                //     RCSPOpLargeFileTransfer?.excuteTransferTask({
                                //         fileBuffer: uint8,
                                //         sdCardBean: this.sdCardBean,
                                //         isSupportPackageCrc16: true,
                                //         fileName: fileName,
                                //         lastModifyTime: tempFilePaths[0].time,
                                //         fileNameEncodeFormat: 0,
                                //         callback
                                //     })
                                // }
                            }, complete: (_res) => {
                                fs.close({ fd })
                            }
                        })
                    }
                })

            }
        })
    },
    // inputFileNmae(e: any) {
    //     var value = e.detail.value
    //     console.log(" tas " + value);

    //     this.setData({
    //         fileName: value
    //     })
    // }
})